import { defineStore } from 'pinia'
import { deleteUserById, editUserData, newUserData, postUsersListData } from '@/services/main/system/user/user'
import type { IUser, IUserInfo, IUserList, IUserResponse } from '@/services/main/system/user/type'
import type { IStore } from './type'
import useMainStore from '../../main'

const useUserStore = defineStore('user', {
  state: (): IStore => ({
    usersList: [],
    totalCount: 0,
    loading: false,
    pageSize: 10,
    currentPage: 1
  }),
  actions: {
    async postUserListAction(queryInfo: IUser) {
      try {
        this.loading = true
        const res: IUserResponse = await postUsersListData(queryInfo)

        if (res.code == 0 && res.data) {
          this.usersList = res.data.list as IUserList[]
          this.totalCount = res.data.totalCount as number

          // 重新获取用户菜单, 按钮等数据
          const mainStore = useMainStore()
          mainStore.fetchEntireDataAction()
        } else {
          return Promise.reject(new Error('获取用户列表失败'))
        }
      } catch (error) {
        return Promise.reject(new Error('当前接口异常，请联系管理员'))
      } finally {
        this.loading = false
      }
    },
    async deleteUserByIdAction(id: number) {
      try {
        const size = this.pageSize
        const offset = (this.usersList.length > 0 ? this.currentPage - 1 : this.currentPage - 2) * size
        const res = await deleteUserById(id)
        if (res.code == 0) {
          this.postUserListAction({ offset: offset, size: size })

          // 重新获取用户菜单, 按钮等数据
          const mainStore = useMainStore()
          mainStore.fetchEntireDataAction()
        } else {
          return Promise.reject(new Error('删除用户失败'))
        }
      } catch (error) {
        return Promise.reject(new Error('删除用户失败'))
      }
    },
    async newUserDataAction(useInfo: IUserInfo) {
      try {
        const res = await newUserData(useInfo)
        if (res.code == 0) {
          this.postUserListAction({ offset: 0, size: 10 })

          // 重新获取用户菜单, 按钮等数据
          const mainStore = useMainStore()
          mainStore.fetchEntireDataAction()
        } else {
          return Promise.reject(new Error('创建用户失败'))
        }
      } catch (error) {
        return Promise.reject(new Error('创建用户失败'))
      }
    },
    async editUserDataAction(id: number, useInfo: IUserInfo) {
      try {
        const size = this.pageSize
        const offset = (this.currentPage - 1) * size
        const res = await editUserData(id, useInfo)
        if (res.code == 0) {
          this.postUserListAction({ offset: offset, size: size })

          // 重新获取用户菜单, 按钮等数据
          const mainStore = useMainStore()
          mainStore.fetchEntireDataAction()
        } else {
          return Promise.reject(new Error('更新用户失败'))
        }
      } catch (error) {
        return Promise.reject(new Error('更新用户失败'))
      }
    }
  }
})

export default useUserStore
